package com.lj.universalframework.ui

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.lj.universalframework.enum.NetworkChanges
import com.lj.universalframework.enum.NetworkStatus
import com.lj.universalframework.enum.NetworkType
import com.lj.universalframework.http.RequestViewModel
import com.lj.universalframework.utils.AppManager
import com.lj.universalframework.utils.CommonUtil
import com.lj.universalframework.utils.NetworkChangeUtils
import com.lj.universalframework.utils.OnNetworkChanges

abstract class BaseActivity<VM : RequestViewModel, DB : ViewDataBinding> : AppCompatActivity() {

    protected lateinit var mViewModel: VM
    protected lateinit var mDataBinding: DB

    //网络变化
    protected var networkChanges: OnNetworkChanges? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mDataBinding = CommonUtil.createBinding(this, layoutInflater) as DB
        setContentView(mDataBinding.root)
        mDataBinding.lifecycleOwner = this

        AppManager.instance.addActivity(this)
        mViewModel = ViewModelProvider(this).get(CommonUtil.getClass(this))
        mDataBinding.setVariable(mViewModel.viewId, mViewModel)

        initView()
        initData()
        //监听网络变化
        networkChanges =object :OnNetworkChanges{
            override fun onNetworkChangesList(
                networkStatus: NetworkStatus?,
                networkType: NetworkType?,
                networkChanges: NetworkChanges?
            ) {
                networkStatusChange(networkStatus,networkType,networkChanges)
            }
        }
        NetworkChangeUtils.mInstance.addOnNetworkChanges(networkChanges!!)
    }

    //初始化视图
    open fun initView() {}

    //重新加载
    open fun reLoad() {}

    //网络状态变化
    open fun networkStatusChange(
        networkStatus: NetworkStatus?,
        networkType: NetworkType?,
        networkChanges: NetworkChanges?
    ) {
        Log.i("测试一下","networkStatusChange：networkStatus:${networkStatus?.type}  networkType:${networkType?.type}  networkChanges:${networkChanges?.type}")
    }

    //初始化数据
    abstract fun initData()


    override fun onDestroy() {
        super.onDestroy()
        AppManager.instance.removeActivity(this)
        //移除网络变化通知
        networkChanges?.apply {
            NetworkChangeUtils.mInstance.removeOnNetworkChanges(this)
        }
    }
}